package ru.alt22.visor.php.ui.providers;

import java.util.ArrayList;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.php.internal.core.project.PHPNature;

import ru.alt22.visor.php.core.PDToolsCorePlugin;
import ru.alt22.visor.php.unittests.core.PHPTest;
import ru.alt22.visor.php.unittests.core.PHPTestSuite;
import ru.alt22.visor.php.unittests.run.TestsFactory;

public class TestsTreeContentProvider implements ITreeContentProvider {
	private static final Object[] NO_ELEMENTS = new Object[0];

	public Object[] getChildren(Object parentElement) {
		if (parentElement instanceof IProject) {
			return TestsFactory.getFinder().find((IProject) parentElement).getTests().toArray();
		}
		if (parentElement instanceof PHPTestSuite) {
			PHPTestSuite suite = (PHPTestSuite) parentElement;
			return suite.getTests().toArray(new PHPTest[suite.getTests().size()]);
		}
		return NO_ELEMENTS;
	}

	public Object getParent(Object element) {
		return null;
	}

	public boolean hasChildren(Object element) {
		if (element instanceof IProject) {
			return TestsFactory.getFinder().find((IProject) element).countTestCases() > 0;
		}
		if (element instanceof PHPTestSuite) {
			PHPTestSuite suite = (PHPTestSuite) element;
			return (suite.countTestCases() > 0);
		}
		return false;
	}

	public Object[] getElements(Object inputElement) {
		if (inputElement instanceof String) {
			ArrayList<IProject> result = new ArrayList<IProject>();
			IProject[] projects = PDToolsCorePlugin.getWorkspace().getRoot().getProjects();

			for (int i = 0; i < projects.length; i++) {
				IProject project = projects[i];
				try {
					if (!project.exists() || !project.isOpen() || !project.hasNature(PHPNature.ID)) {
						continue;
					}
					if (TestsFactory.getFinder().find(project).getTests().size() == 0) {
						continue;
					}
					result.add(project);
				} catch (CoreException e) {}
			}
			return result.toArray();
		}
		return NO_ELEMENTS;
	}

	public void dispose() {
	}

	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
	}

}
